import { ElementRef } from "@angular/core";
import { ACESFilmicToneMapping, PerspectiveCamera, Scene, WebGLRenderer } from "three";
import { ThreeRenderer } from "../three/renderer";
import { Perspective } from "../camera/perspective";
import { RobotScene } from "../scene/robot";
import { OrbitControls } from "three/examples/jsm/Addons.js";

export class RobotRenderer {

    private perspective = new Perspective();
    private threeRenderer = new ThreeRenderer();
    private robotScene = new RobotScene();
    private camera: PerspectiveCamera = new PerspectiveCamera;
    private renderer: WebGLRenderer;
    private scene: Scene;
    private oControls!: OrbitControls;

    private elementRef!: ElementRef;



    constructor() {
        this.renderer = this.threeRenderer.webGL();
        this.scene = this.robotScene.init()
    }

    init(elementRef: ElementRef) {
        this.elementRef = elementRef;
        this.camera = this.perspective.init(75, this.elementRef.nativeElement.offsetWidth / this.elementRef.nativeElement.offsetHeight, 1, 1100)
        this.camera.lookAt(0, -1, 10)
        this.camera.position.set(1, 1, 1);

        this.renderer.setPixelRatio(1);
        this.renderer.setSize(this.elementRef.nativeElement.offsetWidth, this.elementRef.nativeElement.offsetHeight);

        this.oControls = new OrbitControls(this.camera, this.elementRef.nativeElement);
        

        return this.renderer;
    }

    animate() {
        requestAnimationFrame(this.animate.bind(this));
        this.oControls.update();
        this.robotScene.animate();
        this.renderer.render(this.scene, this.camera);
    }

    onMouseDown(event: MouseEvent) {
        this.robotScene.play()
    }
    onMouseMove(event: MouseEvent) {
 
    }
    onMouseUp(event: MouseEvent) {

    }
    onMouseWheel(event: WheelEvent) {
        this.camera.fov += event.deltaY * 0.05;
        if (this.camera.fov < 20) {
            this.camera.fov = 20
        } else if (this.camera.fov > 100) {
            this.camera.fov = 100
        }
        this.camera.updateProjectionMatrix();
    }

    onWindowResize() {
        this.camera.aspect = this.elementRef.nativeElement.offsetWidth / this.elementRef.nativeElement.offsetHeight;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(this.elementRef.nativeElement.offsetWidth, this.elementRef.nativeElement.offsetHeight);
    }

}